package com.dsunsoft.rtu.service.impl;

import com.dsunsoft.rtu.common.constant.CommonConstants;
import com.dsunsoft.rtu.dao.SysRoleMapper;
import com.dsunsoft.rtu.dao.SysUserMapper;
import com.dsunsoft.rtu.entity.SysRole;
import com.dsunsoft.rtu.entity.SysUser;
import com.dsunsoft.rtu.properties.OAuthProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 账号验证
 *
 * @author ygm
 */
@Component("userDetailService")
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.selectByName(userName);
        if (null == sysUser) {
            throw new UsernameNotFoundException(userName);
        }
        List<SysRole> roleList = sysRoleMapper.selectRoleByUserId(sysUser.getId());
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        for (SysRole role : roleList) {
            grantedAuthorityList.add(new SimpleGrantedAuthority(role.getRoleCode()));
        }
        boolean isEnabled = CommonConstants.ONE.equals(sysUser.getStatus());
        return new User(sysUser.getId(), sysUser.getPassword(), isEnabled, true, true, true, grantedAuthorityList);
    }

}
